package com.hugehard.endpointsearch;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class EndPointSearchActivity extends Activity {

	private volatile UDPServer mServerThread = null;
	
	private ListView mListView = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_end_point_search);

		ArrayList<String> itemArray;
		ArrayAdapter<String> itemAdapter;

		mListView = (ListView) findViewById(R.id.listview);
		itemArray = new ArrayList<String>();
		itemArray.clear();
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1, itemArray);
		mListView.setAdapter(itemAdapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent intent = new Intent(EndPointSearchActivity.this,
						ChatActivity.class);
				intent.putExtra("IP", mListView.getItemAtPosition(position).toString());
				startActivity(intent);
			}
		});

		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
				(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
				(ipAddress >> 24 & 0xff));

		mServerThread = new UDPServer();
		mServerThread.start();

		ScanTask scanTask = new ScanTask(itemArray, itemAdapter);
		scanTask.execute(ip);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mServerThread.cancel();
		mServerThread = null;
	}
}